/**
 * Copyright 2009, OpenScriptures.org
 * GPL 3 License: http://www.gnu.org/licenses/gpl.html
 * $Id: slinking.js 136 2009-02-11 20:25:21Z WestonRuter@gmail.com $
 */



////Persistant list code from Sortable Lists Using jQuery UI <http://www.shopdev.co.uk/blog/sortable-lists-using-jquery-ui/>
//var $manuscriptOL;
//var manuscriptListSelector = "form ol";
//var manuscriptOrderCookieName = "manuscriptOrder";
//
//// write the list order to a cookie
//function registerManuscriptOrder() {
//	$.cookie(manuscriptOrderCookieName, $manuscriptOL.sortable("toArray"), { expires: 7, path: "/" });
//}
//
//// restore the list order from a cookie
//function restoreManuscriptOrder() {
//	var list = $manuscriptOL;
//	if (list == null) return;
//	
//	// fetch the cookie value (saved order)
//	var cookie = $.cookie(manuscriptOrderCookieName);
//	if (!cookie) return;
//	
//	// make array from saved order
//	var IDs = cookie.split(",");
//	
//	// fetch current order
//	var items = list.sortable("toArray");
//	
//	// make array from current order
//	var rebuild = new Array();
//	for ( var v=0, len=items.length; v<len; v++ ){
//		rebuild[items[v]] = items[v];
//	}
//	
//	for (var i = 0, n = IDs.length; i < n; i++) {
//		
//		// item id from saved order
//		var itemID = IDs[i];
//		
//		if (itemID in rebuild) {
//		
//			// select item id from current order
//			var item = rebuild[itemID];
//			
//			// select the item according to current order
//			var child = $manuscriptOL.children("#" + item);
//			
//			// select the item according to the saved order
//			var savedOrd = $manuscriptOL.children("#" + itemID);
//			
//			// remove all the items
//			child.remove();
//			
//			// add the items in turn according to saved order
//			// we need to filter here since the "ui-sortable"
//			// class is applied to all ul elements and we
//			// only want the very first!  You can modify this
//			// to support multiple lists - not tested!
//			$manuscriptOL.filter(":first").append(savedOrd);
//		}
//	}
//}

$(function(){
	var $mssOL = $('ol#mss');
	
	//Disable the submit button if one of the lists is empty or if there are some checkboxes that aren't checked
	//function checkFormState(){
	//	if(!$mssOL.filter(':has(:checked)').length){
	//		$('form button').attr('disabled', 'disabled'); //.attr('title', 'There must be at least one manuscript in both the insertion list and the deletion list.');
	//		return false;
	//	}
	//	else {
	//		$('form button').removeAttr('disabled'); //.removeAttr('title');
	//		return true;
	//	}
	//}

	//When clicking the introduction link, add the target class to make it appear
	$('#introduction p:first-child a').click(function(e){
		$('#introduction').addClass('target');
		//$(window).resize(); //re-calculate the position of the fixed headers
		e.preventDefault();
	});
	
	//Before submitting the form, check first to see if it is valid
	$('form').submit(function(e){
		//if(!checkFormState()){
		//	e.preventDefault();
		//	return;
		//}
		$('form button').text('Please wait... request may take a few seconds')
		                .attr('disabled', 'disabled')
						.addClass('working')
						.blur();
		//registerManuscriptOrder();
	});
	
	//Whenever a checkbox is clicked, re-check the form state
	//$mssOL.find('li input[type=checkbox]').click(function(){
	//	checkFormState();
	//});
	
	//Make each of the two lists sortable, that is, re-orderable
	$mssOL.sortable({
		axis: "y",
		cursor: "move"
	});
	
	//Prevent clicking on label or checkbox from initiating sortable
	$mssOL.find('label, input').mousedown(function(e){
		e.stopPropagation();
	});

	
	
	
	// reinstate the user's order upon last form submission
	//restoreManuscriptOrder();
	
	//TEMP: Make sure that only two manuscripts are selected
	
	//var allChecked = $('form ol input:checked').get();
	//while(allChecked.length > 2){
	//	allChecked[0].checked = false;
	//	allChecked.shift();
	//}
	//$('form ol input[type=checkbox]').click(function(e){
	//	if(this.checked){
	//		while(allChecked.length >= 2){
	//			allChecked[0].checked = false;
	//			allChecked.shift();
	//		}
	//		allChecked.push(this);
	//	}
	//	else {
	//		var that = this;
	//		allChecked = $(allChecked).filter(function(){
	//			return this != that;
	//		}).get();
	//	}
	//});
	
	//Highlight the corresponding equivalent tokens between the two manuscripts
	//$($('#parallel').length ? '#parallel p span, #parallel p del, #parallel p ins' : '#unified  p span, #unified  p del, #unified  p ins')
	$($('#parallel').length ? '#parallel p *[id]' : '#unified  p *[id]') 
		.live('mouseover', function(e){
			//Stop if already highlighted (prevents infinite recursion)
			if($(this).hasClass('highlight'))
				return;
			$(this).addClass('highlight');
			
			//Highlight equivalent words
			if(this.id.substr(0,1) != 't'){
				var otherId = (this.id.substr(0, 1) == 'i' ? 'd' : 'i') + this.id.substr(1);
				$('#' + otherId).mouseover();
			}
			
			//Highlight inline transposed words
			if(tokenInfo[this.id].inlineTranspositions){
				$(tokenInfo[this.id].inlineTranspositions).each(function(){
					//$(this).mouseover(); //Don't do this because it will also highlight the token's works
					$(this).addClass('transposedHighlight');
				});
			}
			
			//Highlight translateral transposed words (first in INS side, second in DEL side)
			if(tokenInfo[this.id].translateralTranspositions){
				$(tokenInfo[this.id].translateralTranspositions).each(function(){
					$(this).mouseover();
				});
			}
			
			//Highlight the titles of this unique word's work 
			if(tokenInfo[this.id] && tokenInfo[this.id].w){
				$(tokenInfo[this.id].w).each(function(){
					$('#name' + this).addClass('highlight');
				});
			}
			
			//Gather token parsings for display
			if(window.tokenInfo[this.id] && !window.tokenInfo[this.id].p){
				console.warn(this, window.tokenInfo[this.id])
				return;
			}
			if(!this.title && window.tokenInfo[this.id] && tokenInfo[this.id].p.length){
				var parsingParts = [];
				var strongsObtained = {};
				$(tokenInfo[this.id].p).each(function(){
					var parse = [];
					if(this.parse)
						parse.push(this.parse);
					if(this.lemma)
						parse.push(this.lemma);
					if(this.strongs){
						if(!window.strongsGreekDictionary){
							parse.push(this.strongs); //just include the strong's numbers if definitions aren't available
						}
						else {
							$(this.strongs.split(/;/)).each(function(){
								if(strongsObtained[this])
									return;
								parse.push(this);
								var entry = strongsGreekDictionary[this];
								if(entry){
									parse.push(' ' + entry.lemma);
									if(entry.strongs_def)
										parse.push(' ' + entry.strongs_def);
									if(entry.kjv_def)
										parse.push(' ' + entry.kjv_def);
									if(entry.derivation)
										parse.push(' ' + entry.derivation);
								}
								strongsObtained[this] = true;
							});
						}
						//parse.push(this.strongs);
					}
					parsingParts.push(parse.join(' '));
				});
				
				this.title = parsingParts.join('; ');
			}
		})
		.live('mouseout', function(){
			//Stop if already highlighted (prevents infinite recursion)
			if(!$(this).hasClass('highlight'))
				return;
			$(this).removeClass('highlight');
			
			//Un-highlight equivalent words
			if(this.id.substr(0,1) != 't'){
				var otherId = (this.id.substr(0, 1) == 'i' ? 'd' : 'i') + this.id.substr(1);
				$('#' + otherId).mouseout();
			}
			
			//Unhighlight inline transposed words
			if(tokenInfo[this.id].inlineTranspositions){
				$(tokenInfo[this.id].inlineTranspositions).each(function(){
					//$(this).mouseout();
					$(this).removeClass('transposedHighlight');
				});
			}
			
			//Highlight translateral transposed words (first in INS side, second in DEL side)
			if(tokenInfo[this.id].translateralTranspositions){
				$(tokenInfo[this.id].translateralTranspositions).each(function(){
					$(this).mouseout();
				});
			}
			
			//Un-highlight the titles of this unique word's work 
			if(tokenInfo[this.id] && tokenInfo[this.id].w){
				$(tokenInfo[this.id].w).each(function(){
					$('#name' + this).removeClass('highlight');
				});
			}
		});
	
	$(document.documentElement).addClass('loaded');
	$('#loadingNotice').attr('hidden', 'hidden');
});
